var express = require("express");
var router = express.Router();

const usersApi = require("../api/users");

/* GET users listing. */
router.get("/", function (req, res, next) {
  res.send("respond with a resource");
});

router.post("/login", async function (req, res, next) {
  const { username, password } = req.body;
  const data = await usersApi.login({ username, password });
  data
    ? res.send({ state: true, id: data._id, username: data.username })
    : res.send({ state: false });
});

router.get("/check", async function (req, res, next) {
  const { username } = req.query;
  const data = await usersApi.check(username);

  data ? res.send({ state: true }) : res.send({ state: false });
});

router.post("/reg", async function (req, res, next) {
  const { username, password, role } = req.body;
  await usersApi.reg({ username, password, role });

  res.send({ state: true });
});

router.get("/getMsg", async function (req, res, next) {
  const { curPage, eachPage } = req.query;
  const data = await usersApi.getMsg(curPage, eachPage);

  res.send(data);
});

router.post("/updateUser", async function (req, res, next) {
  const { id, phone, address } = req.body;
  await usersApi.update(id, phone, address);

  res.send({ state: true });
});

router.post("/addUser", async function (req, res, next) {
  const { username, password, role, address, phone } = req.body;
  await usersApi.addUser({ username, password, role, address, phone });
  res.send({ state: true });
});

router.get("/searchUser", async function (req, res, next) {
  const { username, curPage, eachPage } = req.query;
  let data = "";
  if (username != "") {
    data = await usersApi.search(username, curPage, eachPage);
  } else {
    data = await usersApi.getMsg(curPage, eachPage);
  }
  res.send({ data });
});
module.exports = router;
